﻿var zombies = zombies || {};

zombies.publisherIndex = function () {
    var self = this;

    //Edit Adv
    self.AdvId = ko.observable();
    self.Title = ko.observable();
    self.ProductName = ko.observable();
    self.Description = ko.observable();
    self.ShortDes = ko.observable();
    self.Views = ko.observable();
    self.Rate = ko.observable();
    self.Likes = ko.observable();
    self.DateCreated = ko.observable();
    self.CompanyName = ko.observable();
    self.Categories = ko.observableArray();
    self.Medias = ko.observableArray();
    self.Name = ko.observable();
    self.PreviewImg = ko.observable();

    self.CurrentPage = ko.observable(1);

    //collections
    self.Advertises = ko.observableArray();

    self.level = ko.observable();

    self.doChange = function () {
        var option = self.level();
        self.CurrentPage(1);
        switch (option) {
            case '0':
                self.Advertises.removeAll();
                loadAdvertise(self.CurrentPage(), 20, 0);
                break;
            case '1':
                self.Advertises.removeAll();
                loadAdvertise(self.CurrentPage(), 20, 1);
                break;
            case '2':
                self.Advertises.removeAll();
                loadAdvertise(self.CurrentPage(), 20, 3);
                break;
            case '3':
                self.Advertises.removeAll();
                loadAdvertise(self.CurrentPage(), 20, 2);
                break;
        }
    };

    self.setEditView = function (item) {
        self.AdvId(item.AdvId);
        self.Title(item.Title);
        self.ProductName(item.ProductName);
        self.Description(item.Description);
        CKEDITOR.instances['ckeditor-des'].setData(item.Description);
        self.ShortDes(item.ShortDes);
        self.Views(item.Views);
        self.Rate(item.Rate);
        self.Likes(item.Likes);
        self.DateCreated(moment(item.DateCreated).format("dddd, MMMM D, YYYY"));
        self.CompanyName(item.CompanyName);
        self.Name(item.Name);
        self.PreviewImg(item.PreviewImg);
        self.Categories.removeAll();
        self.Medias.removeAll();
        $.ajax({
            url: '/api/AdminAdv/GetCategpriesByAdv/' + item.AdvId,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (items) {
            $.each(items, function (idx, item) {
                self.Categories.push(new zombies.Category(item));
            });
        }).error(function () {
            toastr.error('Lỗi');
        })
        $.ajax({
            url: '/api/AdminAdv/GetMediaByAdv/' + item.AdvId,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (items) {
            $.each(items, function (idx, item) {
                self.Medias.push(new zombies.Media(item));
            });
        }).error(function () {
            toastr.error('Lỗi');
        })
        $('#lst').fadeOut();
        $('#edit').fadeIn();
    };

    self.doDelete = function (item) {
        var advDel = ko.utils.arrayFirst(self.Advertises(), function (i) {
            return i.AdvId === item;
        });
        $.ajax({
            type: "DELETE",
            url: "/api/AdminAdv/DeleteAdvertise/" + item,
            success: function (data) {
                self.Advertises.remove(advDel);
                toastr.success("Xóa Thành Công !");
                $('.reveal-modal').find('[data-confirm-cancel]').trigger('click');
            },
            error: function (error) {
                toastr.error("Xóa Thất Bại !");
            }
        });

    };

    self.doEdit = function (formElement) {
        var advertise = ko.utils.arrayFirst(self.Advertises(), function (item) {
            return item.AdvId === self.AdvId();
        });

        var dataToEdit = {
            AdvId: self.AdvId,
            Title: self.Title,
            ProductName: self.ProductName,
            Description: CKEDITOR.instances['ckeditor-des'].getData(),
            ShortDes: self.ShortDes
        };

        if ($(formElement).valid()) {
            $.ajax({
                type: "PUT",
                url: "/api/AdminAdv/PutAdvertise",
                data: ko.toJSON(dataToEdit), //Convert the Observable Data into JSON
                contentType: "application/json",
                dataType: 'json'
            }).done(function () {
                toastr.success('Chỉnh Sửa Thông Tinh QC Thành Công!');
                self.Advertises.replace(advertise, {
                    AdvId: self.AdvId(),
                    Title: self.Title(),
                    ProductName: self.ProductName(),
                    ShortDes: self.ShortDes(),
                    Description: CKEDITOR.instances['ckeditor-des'].getData(),
                    Views: self.Views(),
                    Rate: self.Rate(),
                    Likes: self.Likes(),
                    DateCreated: self.DateCreated(),
                    CompanyName: self.CompanyName(),
                    Categories: self.Categories(),
                    Medias: self.Medias(),
                    Name: self.Name(),
                    PreviewImg: self.PreviewImg()
                });
                $('#lst').fadeIn();
                $('#edit').fadeOut();
            }).fail(function () {
                toastr.error('Edit Advertise Failed !');
            });
        }
    };

    self.doBack = function () {
        $('#lst').fadeIn();
        $('#edit').fadeOut();
    }

    self.loadMore = function () {
        var num = self.CurrentPage() + 1;
        loadAdvertise(num, 20, self.level())
    }
};

//load data functions
var loadAdvertise = function (page, elementQ, oderBy) {
    $.ajax({
        type: "GET",
        url: "/api/Publisher/GetAdvByCurrentPub",
        data: { page: page, elementQ: elementQ, orderBy: oderBy },
        contentType: "application/json",
        dataType: 'json'
    }).done(function (items) {
        for (i in items) {
            if (items.hasOwnProperty(i)) {
                pubIndexModel.Advertises.push(new zombies.Advertise(items[i]));
            }
        };
    }).fail(function () {
        toastr.error('Lỗi bất thường');
    });
};

var pubIndexModel;
$(document).ready(function () {
    pubIndexModel = new zombies.publisherIndex();
    pubIndexModel.Advertises.removeAll();
    //loadChanel();

    ko.applyBindings(pubIndexModel, document.getElementById("content_publisher"));
});

